package com.example.datajdbc.ext.spring.data.jdbc;

import org.springframework.data.jdbc.repository.query.JdbcQueryMethod;
import org.springframework.data.repository.query.QueryMethod;
import org.springframework.data.repository.query.RepositoryQuery;
import org.springframework.util.Assert;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MybatisQuery implements RepositoryQuery {

    private final Method method;
    private final JdbcQueryMethod queryMethod;
    private final Object mybatisMapper;

    public MybatisQuery(final Method method, final JdbcQueryMethod queryMethod, final Object mybatisMapper) {
        Assert.notNull(queryMethod, "Query method must not be null");
        Assert.notNull(mybatisMapper, "Mybatis Mapper must not be null");

        this.method = method;
        this.queryMethod = queryMethod;
        this.mybatisMapper = mybatisMapper;
    }

    @Override
    public Object execute(final Object[] parameters) {
        try {
            return this.method.invoke(this.mybatisMapper, parameters);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new UnsupportedOperationException("Method are not supported using mybatis-based queries; Offending method: " + queryMethod);
        }
    }

    @Override
    public QueryMethod getQueryMethod() {
        return this.queryMethod;
    }

}
